import { _decorator, Component, Node, RigidBody2D, Vec2, Vec3 } from 'cc';
import { GravityWell } from './GravityWell';
const { ccclass, property } = _decorator;

@ccclass('GravityController')
export class GravityController extends Component {
    
    @property(Node)
    player: Node = null!;  // 玩家节点
    
    @property(Node)
    gravityWellsParent: Node = null!;  // 引力井容器节点
    
    private playerRigidBody: RigidBody2D = null!;
    
    onLoad() {
        // 获取玩家刚体组件
        if (this.player) {
            this.playerRigidBody = this.player.getComponent(RigidBody2D)!;
        }
    }
    
    update(deltaTime: number) {
        if (!this.playerRigidBody || !this.gravityWellsParent) return;
        
        // 获取玩家位置
        const playerPos = this.player.getPosition();
        
        // 调试信息
        
        // 计算所有引力井对玩家的总作用力
        let totalForce = new Vec2(0, 0);
        
        // 遍历所有活跃的引力井
        for (let i = 0; i < this.gravityWellsParent.children.length; i++) {
            const wellNode = this.gravityWellsParent.children[i];
            const wellComponent = wellNode.getComponent(GravityWell);
            
            if (wellComponent && wellNode.active) {
                // 计算这个引力井对玩家的引力
                const force = wellComponent.calculateGravity(playerPos);
                // 使用新的Vec2对象避免修改只读属性
                totalForce = new Vec2(totalForce.x + force.x, totalForce.y + force.y);
            }
        }
        
        
        // 限制最大合力，防止速度过快
        const maxForce = 2000;
        const forceLength = Math.sqrt(totalForce.x * totalForce.x + totalForce.y * totalForce.y);
        if (forceLength > maxForce) {
            const normalizedX = totalForce.x / forceLength;
            const normalizedY = totalForce.y / forceLength;
            totalForce = new Vec2(normalizedX * maxForce, normalizedY * maxForce);
        }
        
        // 对玩家施加合力
        if (forceLength > 0) {
            const scaledForce = new Vec2(totalForce.x * deltaTime, totalForce.y * deltaTime);
            this.playerRigidBody.applyForceToCenter(scaledForce, true);
        }
        
        // 限制最大速度，防止玩家飞得太快
        const currentVelocity = this.playerRigidBody.linearVelocity;
        const maxSpeed = 500;
        const velocityLength = Math.sqrt(currentVelocity.x * currentVelocity.x + currentVelocity.y * currentVelocity.y);
        if (velocityLength > maxSpeed) {
            const normalizedVelX = currentVelocity.x / velocityLength;
            const normalizedVelY = currentVelocity.y / velocityLength;
            const limitedVelocity = new Vec2(normalizedVelX * maxSpeed, normalizedVelY * maxSpeed);
            this.playerRigidBody.linearVelocity = limitedVelocity;
        }
    }
}